#coding=utf-8 
import sublime, sublime_plugin
import time
import re

SETTINGS_FILE = "\'Timestamp.sublime-settings"
SETTINGS_FILE = SETTINGS_FILE.strip(r"\"|\'")

print(SETTINGS_FILE)
class TimestempCommand(sublime_plugin.TextCommand):
	def run(self, edit):

		file_name = self.view.file_name()
		
		suffix = file_name.split('.')
		suffix = suffix[-1]

		mark = self.view.sel()[0]

		if mark.a > mark.b:
			markStart = mark.b
		else:
			markStart = mark.a

		word = self.view.substr(mark)
		timenum = time.strftime("%Y%m%d%H%M%S", time.localtime())

		if sublime.get_clipboard() and is_number(sublime.get_clipboard()):
			timenum = sublime.get_clipboard()

		timestamp = "v="+timenum
		if mark.a == mark.b:
			self.view.replace(edit, mark, timestamp)
		elif is_number(word):
			self.view.replace(edit, mark, timenum)
		else:
			settings = sublime.load_settings(SETTINGS_FILE)

			if suffix == "css" or suffix == "scss" or suffix == "sass":
				findall = re.findall(r'url\((.*?)\)', word)
			elif suffix == "html" or suffix == "php":
				findall = re.findall(r'src=\"(.*?)\"|href=\"(.*?)\"', word)
			else:
				return
			
			# print(findall)

			if findall:
				start = 0
				findallDictonary = []

				# 生成数据数组，保存这记录的开始位置，及长度，长度计算结束位置
				for x in findall:
					if isinstance(x, str) == False:
						x = x[0] or x[1]

					# 删除首部和尾部的引号，主要是css中的url有时会有引号
					x = x.strip(r"\"|\'").lstrip(r"\"|\'")

					start = word.index(x, start+1)
					findallDictonary.append({
						"start": start,
						"data": x,
						"len": len(x)
						})

				for index in range(len(findallDictonary)):
					x = findallDictonary[index]
					newx = getNewX(x, timestamp, suffix)

					start = markStart+newx["start"]
					end = start + newx["len"]
					# 生成数据区间，进行替换数据
					region = sublime.Region(start, end)
					self.view.replace(edit, region, newx["new_data"])

					if index == len(findallDictonary) - 1:
						return

					# 记录上次变化的位置，循环记录，累计把前面的都进行记录下来
					if index>0:
						x["change"] = x["new_len"] - x["len"] + findallDictonary[index-1]["change"]
					else:
						x["change"] = x["new_len"] - x["len"]

					findallDictonary[index + 1]["start"] += x["change"]

			else:
				print ("No match!!")
		

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False

def getNewX(xdata, timestamp, suffix):

	x = xdata["data"]
	prefix = ""

	if suffix == 'php':
		prefix = re.findall(r'(<\?.*?\?>)', x)
		if len(prefix)==0:
			prefix = ""
		else:
			prefix = prefix[0]
			x = x[len(prefix): len(x)]
	
	# print(x)
	if x[-1] == "?":
		xdata["new_data"] = x + prefix + timestamp
	elif x.find("?v=") != -1:
		xdata["new_data"] = re.compile('(\?v=\d*)').sub("?"+timestamp, prefix + x)
	elif x.find("&v=") != -1:
		xdata["new_data"] = re.compile('(\&v=\d*)').sub("&"+timestamp, prefix + x)
	elif x.find("?") != -1:
		xdata["new_data"] = prefix + x+"&"+timestamp
	else:
		xdata["new_data"] = prefix + x+"?"+timestamp

	xdata["new_len"] = len(xdata["new_data"])
	return xdata